package logic

import (
	"context"
	"errors"
	"furni-home/homerpc/homerpc"
	"furni-home/homerpc/internal/svc"
	"furni-home/model"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddHomeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddHomeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddHomeLogic {
	return &AddHomeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddHomeLogic) AddHome(in *homerpc.AddHomeRequest) (*homerpc.AddHomeResponse, error) {
	// todo: add your logic here and delete this line
	class := model.Class{
		Name: in.ClassName,
	}
	err := model.DB.Where("name=?", in.ClassName).FirstOrCreate(&class).Error
	if err != nil {
		return nil, errors.New("分类添加失败")
	}

	brand := model.Brand{
		Name: in.BrandName,
	}
	err = model.DB.Where("name=?", in.BrandName).FirstOrCreate(&brand).Error
	if err != nil {
		return nil, errors.New("品牌添加失败")
	}

	home := model.Home{
		Name:    in.Name,
		Price:   float64(in.Price),
		Stock:   in.Stock,
		Image:   in.Image,
		ClassId: int(class.ID),
		BrandId: int(brand.ID),
	}
	err = model.DB.Create(&home).Error
	if err != nil {
		return nil, errors.New("家具添加失败")
	}
	return &homerpc.AddHomeResponse{
		HomeId: int64(home.ID),
	}, nil
}
